package ServletDemo2;


import entity.Admin;
import util.GokJDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");

        // 1.获取参数
        String name = request.getParameter("name");

        Admin admin;
        try {
            admin = GokJDBCUtil.queryForObject("select * from admin where name=?", Admin.class, name);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("数据库查询出错");
            return;
        }

        if (admin == null) {
            response.getWriter().print("账号可用");
        } else {
            response.getWriter().print("账号重复");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");

        // 2.获取参数
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        // 3.检查密码是否匹配
        if (!password.equals(confirmPassword)) {
            response.getWriter().print("密码不匹配");
            return;
        }

        // 直接将密码存储到数据库
        try {
            int adduser = GokJDBCUtil.update("insert into admin(name,pd) values(?,?)", name, password);
            if (adduser > 0) {
                response.getWriter().print("注册成功");
            } else {
                response.getWriter().print("注册失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("数据库操作出错");
        }
    }
}